﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using com.codebump;
using System.Security.Cryptography;
using AuthorizeNet;
using System.Xml;
using System.IO;
using System.Data;
using System.Net;




public partial class Brainetics_Brainetics : System.Web.UI.Page
{
    DateTime date1 = DateTime.Now;
    protected void Page_Load(object sender, EventArgs e)
    {

        lblTime.Text = date1.ToString("HH:mm");
        if (!IsPostBack)
        {
            if (Request.QueryString.HasKeys())
            {
                if (Request.QueryString["listid"] != String.Empty)
                    Session["listid"] = Request.QueryString["listid"];
                else
                    Session["listid"] = 1;


                if (Request.QueryString["dnis"] != null)
                {
                    Session["dnis"] = Request.QueryString["dnis"];
                }
                else
                {
                    Session["dnis"] = "9999999999";
                }
                if (Request.QueryString["ani"] != null)
                {
                    Session["ani"] = Request.QueryString["ani"];
                }
                else
                {
                    Session["ani"] = "9999999999";
                }

                Session["servername"] = Request.QueryString["servername"];
                Session["projectname"] = Request.QueryString["projectname"];
                Session["campaignname"] = Request.QueryString["campaignname"];
                Session["agentid"] = Request.QueryString["agentid"];
                Session["agentfirst"] = Request.QueryString["agentfirst"];
                Session["agentlast"] = Request.QueryString["agentlast"];
                
                Session["App"] = new DataAccess();
                //((DataAccess)Session["App"]).PutCallData("calldate", string.Format("{0:yyyy/MM/dd}", System.DateTime.Today));
                ((DataAccess)Session["App"]).PutCallData("calldate", System.DateTime.Today.ToString());
                ((DataAccess)Session["App"]).CommitCallData();
            }
            
            //((DataAccess)Session["App"]).PutCallData("webtransfer", "8882785115");
            
            //lblAgentName.Text = (Session["agentfirst"].ToString() + " " + Session["agentlast"].ToString()).Trim();
            Session["cInfo"] = false;

           
        }
       // lblDNIS.Text = Session["dnis"].ToString();
    }

    public string prods = "";
    public double total = 0;
    public string sCust = "";
    public double additionalPay = 0;
    public double shipping = 0;
    public bool bInfoSubmitted = false;
    public string preAuthResponseCode;
    

    //POST LOGIC - For Step or Start pages
    //Add if statements as you add pages
    //For Next and Finish pages it is best to use the index in the if statements as below
    protected void WebWizard_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {

        int page = WebWizard.ActiveStepIndex;
        if (page == WebWizard.WizardSteps.IndexOf(this.Intro))
        {
            return;
        }

        if (page == WebWizard.WizardSteps.IndexOf(this.Offer))
        {
            if (!cbDownsell2.Checked)
            {
                ddlDeluxeQty.SelectedIndex = 0;
            }
            if (!cbDownsell.Checked)
            {
                cbExtraDVDs.Checked = false;
            }

        }

        if (page == WebWizard.WizardSteps.IndexOf(this.ConfirmOrder))
        {
            //if (lblCustDataEntered.Visible)
            //{
            //    //var nextbutton = WebWizard.FindControl("StepNavigationTemplateContainerID").FindControl("StepNextButton") as LinkButton;
            //    ((LinkButton)WebWizard.FindControl("StepNavigationTemplateContainerID").FindControl("StepNextButton")).Visible = false;
            //    return;
            //}
            //else
            //{
            //    //var nextbutton = WebWizard.FindControl("StepNavigationTemplateContainerID").FindControl("StepNextButton") as LinkButton;
            //    ((LinkButton)WebWizard.FindControl("StepNavigationTemplateContainerID").FindControl("StepNextButton")).Visible = true;
            //}



            //if (ddlProducts.SelectedItem.Text == "Choose One" && ddlProducts.Visible)
            //{
            //    lblNoProduct.Visible = true;
            //    return;
            //}
            //else
            //{
            //    lblNoProduct.Visible = false;
            //    //((DataAccess)Session["App"]).PutCallData("webusercode", "RS");
            //    //WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Disposition);
            //    return;
            //}
            
            
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Preauth))
        {
           
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Disposition))
        {
            return;
        }



    }

    //POST LOGIC for disposition pages
    //this is for pages that contain a disposition button
    protected void WebWizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {

        int page = WebWizard.ActiveStepIndex;
        if (page == WebWizard.WizardSteps.IndexOf(this.Intro))
        {
            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.ConfirmOrder))
        {
            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Preauth))
        {
            //Change These two lines of code - For Information Only

            //((DataAccess)Session["App"]).PutCallData("webusercode", "RS");
            //WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Disposition);
            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Disposition))
        {
            return;
        }


    }

    //PRE-LOGIC
    //Add if statements as needed for post-logic
    //You can use the Step ID name instead of the index as used in Next and Finish logic.
    protected void WebWizard_ActiveStepChanged(object sender, EventArgs e)
    {

        if (WebWizard.ActiveStep.Title.ToString() == "OnePayUpsell")
        {
            if (Convert.ToBoolean(Session["cInfo"]) == false)
            {
               // WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.CollectInfo);
               // return;
            }
            
        }

        if (WebWizard.ActiveStep.Title.ToString() == "Upsells")
        {
            if (cbDownsell2.Checked)
            {
                pnlTrial.Visible = true;
            }
            else
            {
                pnlTrial.Visible = false;
            }

            if (!cbDownsell.Checked)
            {
                pnlDeluxe.Visible = false;
            }
            else
            {
                pnlDeluxe.Visible = true;
            }
            if (!cbDownsell2.Checked && !cbDownsell.Checked)
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.MoreUpsells);
            }
        }
        
        if (WebWizard.ActiveStep.Title.ToString() == "NoNoPitch")
        {
            
        }
        if (WebWizard.ActiveStep.Title.ToString() == "ConfirmOrder")
        {
            WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Preauth);
        }

       

        if (WebWizard.ActiveStep.Title.ToString() == "Disposition")
        {
             
            
            //These two lines should be fairly standard - they write the in-memory tables to the Database
            if (btnPreAuth.Enabled)
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Preauth);
                return;
            }
            else
            {
                DispoConfirm1.Visible = false;
                //((DataAccess)Session["App"]).PutCallData("webusercode", "RS"); //RS doesn't exist as a Brainetics usercode in the campaignusercodes table ????

                //foreach (DataRow r in ((DataAccess)Session["App"]).GetOrder().Rows)
                //{
                //    r["calldate"] = string.Format("{0:yyyy/MM/dd}", System.DateTime.Today);
                //}
                buildOrder();
                ((DataAccess)Session["App"]).CommitOrder();
                try
                {
                    
                    Label3.Text = DataPakOrderSubmission();

                        ((DataAccess)Session["App"]).PutCallData("reference_number", Label3.Text);
                        ((DataAccess)Session["App"]).PutCallData("orderdate", string.Format("{0:yyyy/MM/dd}", System.DateTime.Today));
                        ((DataAccess)Session["App"]).PutCallData("webusercode", "BS");
                        ((DataAccess)Session["App"]).CommitCallData();

                }
                catch (Exception ex)
                {
                    lblXMLresult.Text = ex.ToString();
                }
                foreach (System.Data.DataRow r in ((DataAccess)Session["App"]).GetProducts().Rows)
                {
                    ((DataAccess)Session["App"]).RemoveOrderItem(Convert.ToInt32(r["productid"]));
                }
                Response.Redirect("../DispositionComplete.aspx");
            }
            
            

            //((DataAccess)Session["App"]).PutOrderItem(Convert.ToInt32(ddlProducts.SelectedValue) ,1);
            
            
        }

        if (WebWizard.ActiveStep.Title.ToString() == "Preauth")
        {
            lblPreAuthResult.Text = "";
            
                                               
        }

        if (WebWizard.ActiveStep.Title.ToString() == "ConfirmOrder")                                                        //*********   ITEMS ADDED HERE     ****************************
        {
            
            buildOrder();
   
        }

        if (WebWizard.ActiveStep.Title.ToString() == "Rebuttals")
        {
          
        }

    } //end PRE-LOGIC                             //end PRE-LOGIC                        //end PRE-LOGIC                     //end PRE-LOGIC                    //end PRE-LOGIC

    protected void buildOrder()
    {
        ((DataAccess)Session["App"]).GetOrder().Rows.Clear();
        total = 0;
        prods = "";
        additionalPay = 0;
        shipping = 0;

        addMainProd();
        addOtherProds();
        
    }
    protected void addMainProd()
    {
        if (ddlDeluxeQty.SelectedIndex > 0)
        {
            //add discounted deluxe product
            ((DataAccess)Session["App"]).PutOrderItem(491, ddlDeluxeQty.SelectedIndex);
        }
        else if (cbDownsell2.Checked)
        {
            //add trial
            ((DataAccess)Session["App"]).PutOrderItem(490, ddlQty.SelectedIndex);
        }
        else if (cbDownsell.Checked)
        {
            //add basic
            ((DataAccess)Session["App"]).PutOrderItem(489, ddlQty.SelectedIndex);
        }
        else
        {
            //add deluxe
            ((DataAccess)Session["App"]).PutOrderItem(488, ddlQty.SelectedIndex);
        }
    }
    protected void addOtherProds()
    {
        if (cbExtraDVDs.Checked)  //either needs to be this way or have the cb's make the other cb's not checked
        {
            ((DataAccess)Session["App"]).PutOrderItem(497, 1);
        }
        if (ddlMocha.SelectedItem.Value == "Yes")
        {
            ((DataAccess)Session["App"]).PutOrderItem(492, 1);
        }
        if (ddlPlaybookQty.SelectedIndex > 0)
        {
            ((DataAccess)Session["App"]).PutOrderItem(498, 1);
        }
        if (ddlActivityBookQty.SelectedIndex > 0)
        {
            ((DataAccess)Session["App"]).PutOrderItem(499, 1);
        }

        if (ddlSound2.SelectedIndex == 2 || ddlSoundHealth.SelectedIndex == 1)
        {
            //add Sound Health 493:all 3, 494:concentration, 495:learning, 496:thinking
            if (ddlSoundHealth.SelectedItem.Text == "Yes" || ddlSound2.SelectedItem.Text == "3")
            {
                ((DataAccess)Session["App"]).PutOrderItem(493, 1);
            }
            //if (ddlSoundHealth.SelectedItem.Text == "No" && ddlSound2.SelectedItem.Text == "1")
            //{
            //    switch (rblMusic.SelectedIndex)
            //    {
            //        case 0:
            //            ((DataAccess)Session["App"]).PutOrderItem(496, 1);
            //            return;
            //        case 1:
            //            ((DataAccess)Session["App"]).PutOrderItem(495, 1);
            //            return;
            //        case 2:
            //            ((DataAccess)Session["App"]).PutOrderItem(494, 1);
            //            return;
            //    }
            //}
        }
        else if (rblMusic.SelectedIndex >= 0)
        {
            switch (rblMusic.SelectedIndex)
            {
                case 0:
                    //add thinking cd
                    ((DataAccess)Session["App"]).PutOrderItem(496, 1);
                    break;
                case 1:
                    //add learning cd
                    ((DataAccess)Session["App"]).PutOrderItem(495, 1);
                    break;
                case 2:
                    //add concentration cd
                    ((DataAccess)Session["App"]).PutOrderItem(494, 1);
                    break;
                default:
                    //do nothing
                    break;
            }
        }
        if (cbRush.Checked)
        {
            //add rush shipping
            ((DataAccess)Session["App"]).PutOrderItem(500, 1);
        }

    }

    

    protected void btnAutoDiscRebuttal_Click(object sender, EventArgs e)
    {
        
    }

 
    protected void btnSubmit_Click(object sender, System.EventArgs e)
    {
        lblError.Text = "";

        bool bCustValid = false;
        bool ccCheck = false;
        //bool ecCheck = false;
        bool bShipValid = false;

        //int result;

        bCustValid = !(string.IsNullOrEmpty(tbFirstName.Text) ||
            string.IsNullOrEmpty(tbLastName.Text) ||
            string.IsNullOrEmpty(tbAddr.Text) ||
            //string.IsNullOrEmpty(tbAddr2.Text) ||
            string.IsNullOrEmpty(tbZip.Text) ||
            string.IsNullOrEmpty(ddlCity.SelectedItem.Text) ||
            string.IsNullOrEmpty(ddlState.SelectedItem.Text) ||
            string.IsNullOrEmpty(ddlCountry.SelectedItem.Text)) &&
            (ddlCity.SelectedIndex > 0);

        //bCustValid = ! &(string.IsNullOrEmpty(tbFirstName.Text) ||
        //    string.IsNullOrEmpty(tbLastName.Text) ||
        //    string.IsNullOrEmpty(tbAddr.Text) ||
        //    //string.IsNullOrEmpty(tbAddr2.Text) ||
        //    string.IsNullOrEmpty(tbZip.Text) ||
        //    string.IsNullOrEmpty(ddlCity.SelectedItem.Text) ||
        //    ddlState.Items.Count <= 0 ||
        //    string.IsNullOrEmpty(ddlState.SelectedItem.Text) ||
        //    string.IsNullOrEmpty(ddlCountry.SelectedItem.Text)) &&
        //    (ddlCity.SelectedIndex > 0);

        ccCheck = !(string.IsNullOrEmpty(ddlCardType.SelectedItem.Text) ||
            string.IsNullOrEmpty(tbCCNumber.Text) ||
            string.IsNullOrEmpty(tbCCV.Text) ||
            string.IsNullOrEmpty(tbExpDate.Text) || //&&
            (tbExpDate.Text.Length < 4) ||          //this has to be before the convert.toint32 statement on it so it fails before attempting that. Otherwise it throws a yellow screen.
            Convert.ToInt32(tbExpDate.Text.Substring(0, 2)) > 12) &&
            (((DataAccess)Session["App"]).IsValidCC(GetCardType(ddlCardType.SelectedValue), tbCCNumber.Text)) &&
            (System.Text.RegularExpressions.Regex.IsMatch(tbCCV.Text, @"^[\d]+$")) &&
            (System.Text.RegularExpressions.Regex.IsMatch(tbExpDate.Text, @"^[\d]+$"));
            //(Int32.TryParse(tbCCV.Text, out result)) &&
            //(Int32.TryParse(tbExpDate.Text, out result)) &&
            



        //ecCheck = !(string.IsNullOrEmpty(tbBankName.Text) ||
        //    string.IsNullOrEmpty(tbAccNum.Text) ||
        //    string.IsNullOrEmpty(tbRoutNum.Text) ||
        //    string.IsNullOrEmpty(tbBankCity.Text) ||
        //    string.IsNullOrEmpty(tbCheckNum.Text)) &&
        //    (Int32.TryParse(tbAccNum.Text, out result)) &&
        //    (Int32.TryParse(tbRoutNum.Text, out result)) &&
        //    (Int32.TryParse(tbCheckNum.Text, out result));

        //bShipValid = !(string.IsNullOrEmpty(tbShipAddr.Text) ||
        //    //string.IsNullOrEmpty(tbShipaddr2.Text) ||
        //    string.IsNullOrEmpty(tbShipZip.Text) ||
        //    string.IsNullOrEmpty(ddlShipCity.SelectedItem.Text) ||
        //    string.IsNullOrEmpty(ddlShipState.SelectedItem.Text) ||
        //    string.IsNullOrEmpty(ddlShipCountry.SelectedItem.Text)) &&
        //    (ddlShipCity.SelectedIndex > 0) &&
        //    (tbShipZip.Text.Length >= 5) &&
        //    (tbShipZip.Text.Length <= 7);

        bShipValid = !(string.IsNullOrEmpty(tbShipAddr.Text) ||
            //string.IsNullOrEmpty(tbShipaddr2.Text) ||
            string.IsNullOrEmpty(tbShipZip.Text) ||
            string.IsNullOrEmpty(ddlShipCity.SelectedItem.Text) ||
            //ddlShipState.Items.Count > 0 ||
            string.IsNullOrEmpty(ddlShipState.SelectedItem.Text) ||
            string.IsNullOrEmpty(ddlShipCountry.SelectedItem.Text)) &&
            (ddlShipCity.SelectedIndex > 0) &&
            (tbShipZip.Text.Length >= 5) &&
            (tbShipZip.Text.Length <= 7);

        if (bCustValid)
        {
            ((DataAccess)Session["App"]).PutCallData("firstname", tbFirstName.Text);
            ((DataAccess)Session["App"]).PutCallData("lastname", tbLastName.Text);
            ((DataAccess)Session["App"]).PutCallData("address1", tbAddr.Text);
            if (!string.IsNullOrEmpty(tbAddr2.Text))
                ((DataAccess)Session["App"]).PutCallData("address2", tbAddr2.Text);
            else
                ((DataAccess)Session["App"]).PutCallData("address2", "");
            ((DataAccess)Session["App"]).PutCallData("Zip", tbZip.Text);
            ((DataAccess)Session["App"]).PutCallData("City", ddlCity.SelectedItem.Text);
            ((DataAccess)Session["App"]).PutCallData("State", ddlState.SelectedItem.Text);
            ((DataAccess)Session["App"]).PutCallData("Country", ddlCountry.SelectedItem.Text);

            if (!cbShipping.Checked)
            {
                //((DataAccess)Session["App"]).PutCallData("ShipAddress1", tbAddr.Text);
                //if (!string.IsNullOrEmpty(tbAddr2.Text))
                //    ((DataAccess)Session["App"]).PutCallData("ShipAddress2", tbAddr2.Text);
                //else
                //    ((DataAccess)Session["App"]).PutCallData("ShipAddress2", "");
                //((DataAccess)Session["App"]).PutCallData("ShipZip", tbZip.Text);
                //((DataAccess)Session["App"]).PutCallData("ShipCity", ddlCity.SelectedItem.Text);
                //((DataAccess)Session["App"]).PutCallData("ShipState", ddlState.SelectedItem.Text);
                //((DataAccess)Session["App"]).PutCallData("ShipCountry", ddlCountry.SelectedItem.Text);
            }
            else
            {
                if (bShipValid)
                {
                    ((DataAccess)Session["App"]).PutCallData("ShipAddress1", tbShipAddr.Text);
                    if (!string.IsNullOrEmpty(tbShipAddr.Text))
                        ((DataAccess)Session["App"]).PutCallData("ShipAddress2", tbShipaddr2.Text);
                    else
                        ((DataAccess)Session["App"]).PutCallData("ShipAddress2", "");
                    ((DataAccess)Session["App"]).PutCallData("ShipZip", tbShipZip.Text);
                    ((DataAccess)Session["App"]).PutCallData("ShipCity", ddlShipCity.SelectedItem.Text);
                    ((DataAccess)Session["App"]).PutCallData("ShipState", ddlShipState.SelectedItem.Text);
                    ((DataAccess)Session["App"]).PutCallData("ShipCountry", ddlShipCountry.SelectedItem.Text);
                }
                else
                {
                    lblError.Text += "Enter Shipping Info<br/>";
                }
            }
        }
        else
        {
            if (ddlCity.SelectedIndex == 0)
                lblError.Text += "Select a City<br/>";
            else
                lblError.Text += "Enter Valid Customer Data<br/>";
        }

        if ((!string.IsNullOrEmpty(tbPhone.Text)) && ((tbPhone.Text.Length != 10) || !(System.Text.RegularExpressions.Regex.Match(tbPhone.Text, @"^[1-9]\d{2}[1-9]\d{6}$").Success)))
        {
            lblError.Text += "Invalid Phone<br/>";
        }
        else
        {
            if (!string.IsNullOrEmpty(tbPhone.Text))
                ((DataAccess)Session["App"]).PutCallData("PrimaryPhone", tbPhone.Text);
        }

        if ((!string.IsNullOrEmpty(tbEmail.Text)) && !((DataAccess)Session["App"]).IsValidEmail(tbEmail.Text))
        {
            lblError.Text += "Invalid Email<br/>";
        }
        else
        {
            if (!string.IsNullOrEmpty(tbEmail.Text))
                ((DataAccess)Session["App"]).PutCallData("Email", tbEmail.Text);
        }


        if (ddlPaymentType.SelectedIndex == 1) // debit/credit
        {
            ((DataAccess)Session["App"]).PutCallData("PaymentType", ddlPaymentType.SelectedItem.Value);

            if (ccCheck)
            {
                //((DataAccess)Session["App"]).PutCallData("CCType", ddlCardType.SelectedItem.Value);
                //((DataAccess)Session["App"]).PutCallData("CCNumber", ((DataAccess)Session["App"]).EnryptData(tbCCNumber.Text));
                //((DataAccess)Session["App"]).PutCallData("CCV", ((DataAccess)Session["App"]).EnryptData(tbCCV.Text));
                //((DataAccess)Session["App"]).PutCallData("CCExpDate", tbExpDate.Text);
            }
            else
            {
                lblError.Text += "Invalid Card Info<br/>";
            }
        }
        //else if (ddlPaymentType.SelectedIndex == 2) // echeck
        //{
        //    ((DataAccess)Session["App"]).PutCallData("PaymentType", ddlPaymentType.SelectedItem.Value);

        //    if (ecCheck)
        //    {
        //        ((DataAccess)Session["App"]).PutCallData("ECBankName", tbBankName.Text);
        //        ((DataAccess)Session["App"]).PutCallData("BankCity", tbBankCity.Text);
        //        ((DataAccess)Session["App"]).PutCallData("ECAccNumber", tbAccNum.Text);
        //        ((DataAccess)Session["App"]).PutCallData("ECRoutingNumber", tbRoutNum.Text);
        //        ((DataAccess)Session["App"]).PutCallData("ECCheckNumber", tbCheckNum.Text);
        //        ((DataAccess)Session["App"]).PutCallData("ECAccType", ddlAccType.SelectedItem.Text);
        //    }
        //    else
        //    {
        //        lblError.Text += "Invalid Bank Info<br/>";
        //    }
        //}
        else
        {
            //lblError.Text += "Please select a payment method." + Environment.NewLine;
        }

        if (bCustValid == true && ccCheck == true)
        {
            if (cbShipping.Checked && bShipValid == false)
            {
            }
            else
            {
                Session["cInfo"] = true;
            }
        }
        else
        {
            Session["cInfo"] = false;
        }

    }


    protected void ddlPaymentType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlPaymentType.SelectedValue == "CC")
        {
            trCCNumber.Visible = true;
            trCCType.Visible = true;
            trCCExpDate.Visible = true;
            trCCV.Visible = true;
            trECAccNum.Visible = false;
            trECBankName.Visible = false;
            trECCheckNum.Visible = false;
            trECRoutNum.Visible = false;
            trBankCity.Visible = false;
            trECAccType.Visible = false;
        }
        else if (ddlPaymentType.SelectedValue == "EC")
        {
            trCCNumber.Visible = false;
            trCCType.Visible = false;
            trCCExpDate.Visible = false;
            trCCV.Visible = false;
            trECAccNum.Visible = true;
            trECBankName.Visible = true;
            trBankCity.Visible = true;
            trECCheckNum.Visible = true;
            trECRoutNum.Visible = true;
            trECAccType.Visible = true;
        }
        else
        {
            trCCNumber.Visible = false;
            trCCType.Visible = false;
            trCCExpDate.Visible = false;
            trCCV.Visible = false;
            trECAccNum.Visible = false;
            trECBankName.Visible = false;
            trECCheckNum.Visible = false;
            trECRoutNum.Visible = false;
            trECAccType.Visible = false;
            trBankCity.Visible = false;
        }

    }

    protected void cbShipping_CheckedChanged(object sender, EventArgs e)
    {
        if (cbShipping.Checked)
        {
            trShipAddr.Visible = true;
            trShipAddr2.Visible = true;
            trShipCity.Visible = true;
            trShipState.Visible = true;
            trShipCountry.Visible = true;
            trShipZip.Visible = true;
            trShipLbl.Visible = true;
            trShipSearchZip.Visible = true;

        }
        else
        {
            trShipAddr.Visible = false;
            trShipAddr2.Visible = false;
            trShipCity.Visible = false;
            trShipState.Visible = false;
            trShipCountry.Visible = false;
            trShipZip.Visible = false;
            trShipLbl.Visible = false;
            trShipSearchZip.Visible = false;
        }
    }

    protected void btnSearchZip_Click(object sender, EventArgs e)
    {
        ValidateZip(tbZip.Text.ToUpper(), ddlCity, ddlState, ddlCountry);
                ddlState.Enabled = true;
    }

    protected void btnShipSearchZip_Click(object sender, EventArgs e)
    {
        ValidateZip(tbShipZip.Text.ToUpper(), ddlShipCity, ddlShipState, ddlShipCountry);
    }

    protected void ValidateZip(string strZip, DropDownList ddl_City, DropDownList ddl_State, DropDownList ddl_Country)
    {

        ddl_City.Items.Clear();
        ddl_State.Items.Clear();
        ddl_City.Enabled = true;
        ddl_State.Enabled = true;
        if (System.Text.RegularExpressions.Regex.IsMatch(strZip.ToUpper(), @"(^\d{5}$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} +\d{1}[A-Z]{1}\d{1}$)"))
        {
            try
            {
                com.codebump.GeoPlaces g = new com.codebump.GeoPlaces();

                com.codebump.AuthenticationHeader authHeader = new com.codebump.AuthenticationHeader();
                authHeader.SessionID = "6JV2ZA4lgG1YRR+HG+JU27QWk9zI3rpRWY2iG2mzNPcdieEQXfQv0OUY0EZ+pOTxhwI1NCuF7b2oY+U/bozy0mhjFHmpaXvb";
                g.AuthenticationHeaderValue = authHeader;

                com.codebump.GeoPlaceDistance[] places = g.GetPlacesInside(strZip, "");

                for (int i = 0; i < places.Length; i++)
                {
                    com.codebump.GeoPlaceDistance place = places[i];
                    ListItem li = new ListItem(place.ToPlace, place.ToState + "," + place.ToPlace);
                    ddl_City.Items.Add(li);
                }

                ddl_State.Items.Add(ddl_City.SelectedItem.Value.Split(",".ToCharArray())[0]);

                //ddlCity.SelectedIndex = 0;

                if (System.Text.RegularExpressions.Regex.IsMatch(strZip.ToUpper(), @"(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)"))
                {
                    ddl_Country.SelectedValue = "CANADA";
                }
                else
                {
                    ddl_Country.SelectedValue = "USA";
                }

                if (ddl_City.Items.Count <= 0)
                {
                    ddl_City.Items.Add("No Cities Found");
                    ddl_State.Items.Add("No States Found");
                    ddl_City.Enabled = false;
                    ddl_State.Enabled = false;
                }
                else
                {
                    ddl_City.Items.Insert(0, "Select a City");
                    ddl_City.SelectedIndex = 0;
                    ddl_State.Enabled = false;
                }
            }
            catch
            {
                ddl_City.Items.Add("No Cities Found");
                ddl_State.Items.Add("No States Found");
                ddl_City.Enabled = false;
                ddl_State.Enabled = false;
            }
        }
        else
        {
            ddl_City.Items.Add("Invalid Zip");
            ddl_City.Enabled = false;
            ddl_State.Items.Add("Invalid Zip");
            ddl_State.Enabled = false;

        }
    }

    public DataAccess.CardType GetCardType(string cardType)
    {
        switch (cardType)
        {
            case "A":
                return DataAccess.CardType.AmericanExpress;
            case "V":
                return DataAccess.CardType.Visa;
            case "D":
                return DataAccess.CardType.Discover;
            case "M":
                return DataAccess.CardType.MasterCard;
            default:
                return DataAccess.CardType.Visa;
        }
    }



    public void PreAuth2()
    {
        lblPreAuthResult.Text = "";
        String post_url = "https://secure.authorize.net/gateway/transact.dll";
        //String post_url = "https://apitest.authorize.net/xml/v1/request.api";
        Dictionary<string, string> post_values = new Dictionary<string, string>();
        //the API Login ID and Transaction Key must be replaced with valid values
        post_values.Add("x_login", "8H7VgC2aa58");
        post_values.Add("x_tran_key", "829V6pP7h5M8GraP");
        post_values.Add("x_delim_data", "TRUE");
        post_values.Add("x_delim_char", "|");
        post_values.Add("x_relay_response", "FALSE");
        post_values.Add("x_version", "3.1");

        //post_values.Add("x_type", "AUTH_CAPTURE");
        post_values.Add("x_type", "AUTH_ONLY");
        post_values.Add("x_method", "CC");
        post_values.Add("x_card_num", tbCCNumber.Text);
        //post_values.Add("x_card_num", "4111111111111111");
        post_values.Add("x_exp_date", tbExpDate.Text);
        //post_values.Add("x_exp_date", "1111");

        post_values.Add("x_amount", lblAmount.Text);
        //post_values.Add("x_description", "Sample Transaction");
        post_values.Add("x_test_request", "FALSE");          ////////********************* CHANGE TO FALSE FOR PRODUCTION!!! *********************

        //post_values.Add("x_first_name", "John");
        //post_values.Add("x_last_name", "Doe");
        //post_values.Add("x_address", "1234 Street");
        //post_values.Add("x_state", "WA");
        //post_values.Add("x_zip", "98004");
        // Additional fields can be added here as outlined in the AIM integration
        // guide at: http://developer.authorize.net

        // This section takes the input fields and converts them to the proper format
        // for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"
        String post_string = "";

        foreach (KeyValuePair<string, string> post_value in post_values)
        {
            post_string += post_value.Key + "=" + HttpUtility.UrlEncode(post_value.Value) + "&";
        }
        post_string = post_string.TrimEnd('&');

        // create an HttpWebRequest object to communicate with Authorize.net
        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(post_url);
        objRequest.Method = "POST";
        objRequest.ContentLength = post_string.Length;
        objRequest.ContentType = "application/x-www-form-urlencoded";

        // post data is sent as a stream
        StreamWriter myWriter = null;
        myWriter = new StreamWriter(objRequest.GetRequestStream());
        myWriter.Write(post_string);
        myWriter.Close();

        // returned values are returned as a stream, then read into a string
        String post_response;
        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
        using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
        {
            post_response = responseStream.ReadToEnd();
            responseStream.Close();
        }

        // the response string is broken into an array
        // The split character specified here must match the delimiting character specified above
        Array response_array = post_response.Split('|');
        //string[] response_array = post_response.Split('|');
 //       lblPreAuthResult.Text = "response code: " + response_array.GetValue(0) + ", response reason: " + response_array.GetValue(1) ;
       
        // the results are output to the screen in the form of an html numbered list.
        //resultSpan.InnerHtml += "<OL> \n";
        foreach (string value in response_array)
        {
            //resultSpan.InnerHtml += "<LI>" + value + "&nbsp;</LI> \n";
            lblPreAuthResult.Text += ": " + value;
        }
        //resultSpan.InnerHtml += "</OL> \n";
        preAuthResponseCode = response_array.GetValue(0).ToString();
        lblCrap.Text = preAuthResponseCode;
        lblPreAuthResult.Text = "response code: " + response_array.GetValue(0).ToString() + ", response sub code: " + response_array.GetValue(1).ToString() + ", response reason code: " + response_array.GetValue(2).ToString() + ", response reason: " + response_array.GetValue(3).ToString() + ", authorization code: " + response_array.GetValue(4).ToString();
        ((DataAccess)Session["App"]).PutCallData("Webresponse", lblPreAuthResult.Text);
        //lblPreauthCode.Text = "";
        //lblAuthTransID.Text = "";
        lblAuthTransID.Text = response_array.GetValue(6).ToString();
        ((DataAccess)Session["App"]).PutCallData("TransactionID", lblAuthTransID.Text);
        lblPreauthCode.Text = response_array.GetValue(4).ToString();
        ((DataAccess)Session["App"]).PutCallData("AuthCode", lblPreauthCode.Text);
        ((DataAccess)Session["App"]).CommitCallData();
        
    }
 
   
   
    protected void tbFirstName_TextChanged(object sender, EventArgs e)
    {
        sCust = tbFirstName.Text;
        lblName1.Text = tbFirstName.Text;
        lblName2.Text = tbFirstName.Text;
        lblName3.Text = tbFirstName.Text;
        lblName4.Text = tbFirstName.Text;
        lblName5.Text = tbFirstName.Text;
        lblName6.Text = tbFirstName.Text;
        lblName7.Text = tbFirstName.Text;
        lblName8.Text = tbFirstName.Text;
        //lblName9.Text = tbFirstName.Text;
        //lblName10.Text = tbFirstName.Text;
        //lblName11.Text = tbFirstName.Text;
        //lblName12.Text = tbFirstName.Text;
        //lblName13.Text = tbFirstName.Text;
        //lblName14.Text = tbFirstName.Text;
        //lblName15.Text = tbFirstName.Text;
        //lblName16.Text = tbFirstName.Text;
        //lblName17.Text = tbFirstName.Text;
        //lblName18.Text = tbFirstName.Text;
        //lblName19.Text = tbFirstName.Text;
        //lblName20.Text = tbFirstName.Text;
        //lblName21.Text = tbFirstName.Text;

        tbLastName.Focus();
    }

 
    
    protected void btnPreAuth_Click(object sender, EventArgs e)
    {
        preauth();
        btnPreAuth.Enabled = false;
    }

    
    
    protected void ddlWhoFor_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch (ddlWhoFor.SelectedItem.Text)
        {
            case "Self":
                lblWhoFor.Text = "That's great! Over 35% of the people using Brainetics are adults!";
                break;
            case "Child":
                lblWhoFor.Text = "What a fantastic decision you’re making for your child’s future!";
                break;
            case "Grandchild":
                lblWhoFor.Text = "What a wonderful gift this will be in their lives. Let me ask, how many grandchildren do you have?";
                break;
            case "Niece/Nephew":
                lblWhoFor.Text = "What a thoughtful aunt/uncle you are for purchasing a learning tool for your relative!";
                break;
            case "Friend":
                lblWhoFor.Text = "What a thoughtful gift, you’re obviously a very caring friend.";
                break;
            case "Family":
                lblWhoFor.Text = "What an incredible family gift!  The skills you learn together will last a lifetime.";
                break;
            case "Other":
                lblWhoFor.Text = "Well, you’re making a wise decision!";
                break;
            default:
                lblWhoFor.Text = "Well, you’re making a wise decision!";
                break;
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
    }
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch (rblRebuttals.SelectedIndex)
        {
            case 0:
                lblRebuttal.Text = "<p>The risk-free trial lets you try the entire Brainetics program in your home for 30 days. You’ll be able to use the program, learn from it, and see for yourself how it works before you make a decision. When you have had a chance to see how easy and incredibly fun it is to learn with Brainetics and want to continue using it, you have a couple of options available. Either way, you’ll be glad that you called today because Brainetics is an amazing product that has already made a positive change in so many lives. First, let me ask you, will this be for yourself or for a loved one?</p>";
                //downsell version lblRebuttal.Text = "<p>The trial offer for $14.95 is set up so that seven days after the Brainetics program has been sent to you, you will have 30 days to review the entire program, which comes with everything that you saw on TV. So, you won’t be charged for the program until after you have been able to see for yourself that it is worth the investment. I will tell you though that when you pay in full today, you are actually saving over $100 because you are getting a 50% discount on the Deluxe Kit, plus I am waiving the trial fee and shipping and handling.</p>";
                break;
            case 1:
                lblRebuttal.Text = "<p>That's fine, (customer's name), I'll just bring up that price on the product for you, it will just take a minute or two.  While I am doing that, can you tell me what you liked about the Brainetics when you saw it on TV?</p>" + 
                    "Excellent, I'm glad to hear that!  I'm really glad that you called today, because Brainettics is an amazing product that has already made a positive change in many lives!!" +
                    "While I am bringing up the pricing details, do you mind if I ask, are you interested for yourself or is it going to be for someone else?  <i>(Make sure you are listening and RESPONDING -even making notes if necessary, this is invaluable information you can use to make this sale!)</i>";
                break;
            case 2:
                lblRebuttal.Text = "<p>The Deluxe program includes: <br/>" +
"All 7 of the DVD’s in the Brainetics program. This will work you from beginner to expert in the math and memory skills that Mike Byster has taught millions of people. You will also receive the playbook that has lessons and more games, a set of 52 flash cards to work on processing the speed of comprehensioin, a deck of playing cards that will increase mental speed and pattern recognition, a parent’s guide to outline each lesson and the On-the-Move activity book for car trips and entertainment.</p>" +

"<p class=\"blue\">[Only provide this info if caller asks for more detail:]</p>" +

"<ul>" +
" <li>A set of 7 educational DVDs that gradually get more challenging and involved as the program progresses. You’ll be able to do everything from following directions, concentrating and detecting patterns in numbers, overcoming math anxiety through tricks and games, shortcuts to enable you to do complex math in your head, mental multi-tasking, organization, and memory-building! Plus, the last two DVDs help you to really MASTER everything that you have learned, and even be able to teach the Brainetics techniques to others!</li>" +
"<li>  A playbook full of lessons, games, tips, and cool facts and explanations that expand on the lessons learned!</li>" +
"<li>  A set of 52 flash cards that help processing speed and lesson comprehension.</li>" +
"<li>  A deck of playing cards that are used to increase mental speed, pattern recognition, and focus.</li>" +
"<li>  A 'Parent Guide' that outlines each lesson and includes tips on how you can encourage your kids (or family) to show you what they have learned.</li>" +
"<li>  FREE BONUS! An 'On-the-Move' Activity book that is fantastic to use on car trips, the bus, waiting at a restaurant, basically anywhere! It uses dry erase markers so you (and your family) can have fun over and over again reinforcing what you have learned!</li></ul>" +

"<p>Your shipping and handling is free today, you have a full 30 days to review the program, and a 30-day money-back guarantee! So let’s get you started now, OK?</p>";
                break;
            case 3:
                lblRebuttal.Text = "<p>Let me ask what is your hesitation?</p>" +

"<p class=\"blue\">[White Text: Address that need.]</p>" +

"<p>I can understand your hesitation, but remember that Brainetics was featured on 20/20 with a group of students who had NEVER used the techniques before. After a few short lessons, those students and even the interviewer were multiplying complex numbers easily. Best yet, the kids were CONFIDENT in their abilities. It’s that confidence that will best serve you/your child in the future. Take advantage of our 30-day money-back guarantee, use it, and see for yourself. OK?</p>";
                break;
            case 4:
                lblRebuttal.Text = "<p>Brainetics uses math to teach you how to use two parts of your brain at the same time; one part processes information while the other part stores information. It allows your mind to work better and faster at ALL subjects - math, history, science, and languages. Brainetics brings your entire thinking process to a new, higher level. It’s taught in a way that is fun and entertaining so that kids especially are much more inclined to learn it.</p>" +

    "<p>Let me teach you a little technique from Brainetics. You can multiply any number that ends in 5 by itself really easily in your head, for instance 75 X 75.<br/></p>" +
    "<p>- You multiply the tens number first and add one to the second number, so in this case, 7 X 8, which is 56.<br/>" +
    "- Then, multiply the ones numbers, so 5 X 5, which is 25.<br/>" +
    "- We take the first answer, 56, and then second answer, 25, and put them together. So, 5,625 is your answer! And this technique works ALL the time.</p> " +

    "<p>Let’s try another one, we can multiply 25 X 25.</p>" +
    "<p>- First we’ll multiply 2 X 3, which gives us 6.<br/>" +
    "- Then we multiply 5 X 5, which gives us 25.<br/>" +
    "- The answer is 625!</p>" +

"<p>Brainetics starts with simple techniques like these that build to a more general approach to improve not only your math skills, but your memory too! You can memorize names, phone numbers, anything you need to remember and be able to recall that information whenever you need! Let me tell you how you can try Brainetics absolutely risk-free today!</p>";
                break;
            case 5:
                lblRebuttal.Text = "<p>" + tbFirstName.Text + ", your interest was piqued [peeked] enough for you to call today and I’d love the chance to prove to you that this is truly an amazing and life-changing program! I have several options for you on today’s call that may not be available at a later time. Let’s get you started today so that you get the best offer available. OK?</p>";
                break;
            case 6:
                lblRebuttal.Text = "<p>I can understand that. And, that’s exactly why we give you a 30-day money-back guarantee. We want you to be able to see, feel, touch, and experience everything about Brainetics and be as confident as we are in this revolutionary system! Let’s get you started today and save you 50% off the regular price, and give you a chance to try it out absolutely risk-free! Which credit card would you like to use?</p>";
                break;
            case 7:
                lblRebuttal.Text = "<p>Absolutely! I completely support families that make decisions together – that’s the way that we do it in my home too! And this is exactly why we give you a 30-day money-back guarantee. You and your family can use it together. You can learn together, motivate, and challenge each other. You can spend time together as a family improving your learning skills. We are absolutely confident that you and your family will enjoy learning with Brainetics. Remember, when you pay in full today, you can experience Brainetics absolutely RISK-FREE because we are paying for your shipping and handling too! What credit card will you be using today?</p>";
                break;
            case 8:
                lblRebuttal.Text = "<p>I understand your hesitation, but remember that Brainetics was featured on 20/20 with a group of students who had NEVER used the techniques before. Within a few short lessons, those students and even the interviewer were multiplying complex numbers easily. Best yet, the kids were CONFIDENT in their abilities. It’s that confidence that will best serve your child in the future and with school starting, now is the best time to start! Take advantage of our 30-day money-back guarantee, use it, and see for yourself. Will you be using Visa or MasterCard today?</p>";
                break;
            case 9:
                lblRebuttal.Text = "<p>I have a lot of customers who are concerned the program will be too difficult for them. Or, they are just plain afraid they will fail. It’s a part of human nature. It’s funny, we’ve been conditioned to think that math is hard and that improving our memory is work. But it’s just not true! Brainetics will quickly build your confidence with how easy it is to learn. You are encouraged to use it, test it out, challenge us, and see the results with your own eyes. Seeing is believing and we are confident that you will be a believer too! Which credit card would you like to use?</p>";
                break;
            case 10:
                lblRebuttal.Text = "<p>I completely understand how price could be a concern, however; this is an investment in your child’s/family’s future! Brainetics teaches how to focus, follow directions, problem solving, organizational skills, and memory improvement. These are all priceless skills that help not only children in school, but adults as well. These are skills that follow you throughout your life. It’s worth it to try Brainetics and see for yourself. Taking the Deluxe Kit today actually saves you money because if you were to buy the two additional DVDs and the “On-the-Move” Car Games Activity book separately, it would be an additional $60, so you are getting a considerable discount today. Take advantage of the 30-day money-back guarantee, try it, and when you see everyone around you learning and enjoying themselves, you’ll agree that you made the right decision. Plus, with school starting it is the perfect time to get your child a head start! <br /><br />Which credit card will you be using today?</p>";
                break;
            default:
                lblRebuttal.Text = "<p> </p>";
                break;

        }
    }

    protected void btnRebuttal_Click(object sender, EventArgs e)
    {
        if (pnlWizard.Visible)
        {
            pnlRebuttals.Visible = true;
            pnlWizard.Visible = false;
            btnRebuttal.Text = "Return to script";
        }
        else
        {
            pnlRebuttals.Visible = false;
            pnlWizard.Visible = true;
            btnRebuttal.Text = "Rebuttals";
        }

    }

    public string preauth()  
    {
        int errNum = 0;
        string errDesc = "";
        string result = "";

        XmlDocument xmlRequest = new XmlDocument();
        XmlDeclaration declaration = xmlRequest.CreateXmlDeclaration("1.0", "UTF-8", null);
        xmlRequest.AppendChild(declaration);

        XmlElement root = xmlRequest.CreateElement("forwardIt");
        //root.SetAttribute("version", "2.00");

        //XmlElement udiparam = CreateElement(xmlRequest, "UDIParameter", null, null, null);
        XmlElement source = CreateElement(xmlRequest, "source", null, null, null);
        source.AppendChild(CreateElement(xmlRequest, "merchantId", "0123456", null, null));
        //source.AppendChild(CreateElement(xmlRequest, "username", "johndoe", null, null));
        //source.AppendChild(CreateElement(xmlRequest, "password", "x423423", null, null));
        source.AppendChild(CreateElement(xmlRequest, "username", "ailAPIo", null, null));
        source.AppendChild(CreateElement(xmlRequest, "password", "083iwkh", null, null));
        root.AppendChild(source);

        XmlElement ccauth = CreateElement(xmlRequest, "ccAuthorization", null, null, null);
        ccauth.AppendChild(CreateElement(xmlRequest, "referenceNumber", "54321", null, null));
        ccauth.AppendChild(CreateElement(xmlRequest, "amount", ((DataAccess)Session["App"]).GetOrderTotal().ToString(), null, null));
        XmlElement billing = CreateElement(xmlRequest, "billingInfo", null, null, null);
        billing.AppendChild(CreateElement(xmlRequest, "fullName", tbFirstName.Text + " " + tbLastName.Text, null, null));
        billing.AppendChild(CreateElement(xmlRequest, "address1", tbAddr.Text, null, null));
        billing.AppendChild(CreateElement(xmlRequest, "address2", tbAddr2.Text, null, null));
        billing.AppendChild(CreateElement(xmlRequest, "state", ddlState.SelectedItem.Text, null, null));
        billing.AppendChild(CreateElement(xmlRequest, "country", ddlCountry.SelectedItem.Text, null, null));
        billing.AppendChild(CreateElement(xmlRequest, "postalCode", tbZip.Text, null, null));
        ccauth.AppendChild(billing);

        XmlElement card = CreateElement(xmlRequest, "creditCard", null, null, null);
        card.AppendChild(CreateElement(xmlRequest, "number", tbCCNumber.Text, null, null));
        if (ddlCardType.SelectedValue == "V")
        {
            card.AppendChild(CreateElement(xmlRequest, "type", "VI", null, null));
        }
        if (ddlCardType.SelectedValue == "A")
        {
            card.AppendChild(CreateElement(xmlRequest, "type", "AM", null, null));
        }
        if (ddlCardType.SelectedValue == "D")
        {
            card.AppendChild(CreateElement(xmlRequest, "type", "DI", null, null));
        }
        if (ddlCardType.SelectedValue == "M")
        {
            card.AppendChild(CreateElement(xmlRequest, "type", "MA", null, null));
        }
        
        card.AppendChild(CreateElement(xmlRequest, "expirationMonth", tbExpDate.Text.Substring(0,2), null, null));
        card.AppendChild(CreateElement(xmlRequest, "expirationYear", "20" + tbExpDate.Text.Substring(2, 2), null, null));
        if (tbCCV.Text.Length == 4)
        {
            card.AppendChild(CreateElement(xmlRequest, "cvn", tbCCV.Text.Substring(1, 3), null, null));
        }
        else
        {
            card.AppendChild(CreateElement(xmlRequest, "cvn", tbCCV.Text, null, null));
        }
        ccauth.AppendChild(card);
        root.AppendChild(ccauth);

        xmlRequest.AppendChild(root);
        //xmlRequest.Save(@"C:\Users\Aaron.Christensen.FOCUSSERVICES\Documents\Datapak_Preauth_test.xml");                                                    //.............comment out for production!~!

        // Send the Request
        //string response = PostRequest("HTTPS://webservices.datapakservices.com/ForwardITGatewayTest", xmlRequest.OuterXml, ref errNum, ref errDesc); //testing
        string response = PostRequest("HTTPS://webservices.datapakservices.com/ForwardITGateway", xmlRequest.OuterXml, ref errNum, ref errDesc);  //production

        // Handle the HTTP errors
        if (errNum != 0)
        {
            if (errNum == 500)
            {
                // Handle critical OMX errors
                if (!String.IsNullOrEmpty(response))
                {
                    //string errors = "";
                    XmlDocument xmlResponse = new XmlDocument();

                }
            }
            throw new Exception("ERROR " + errNum + ": " + errDesc);
        }
        //result = xmlResponse.LoadXml(response);
        // Handle the response content
        if (!String.IsNullOrEmpty(response))
        {
            XmlDocument xmlResponse = new XmlDocument();
            xmlResponse.LoadXml(response);
            
        //    // XML processing
            if (xmlResponse.SelectSingleNode("/forwardItResponse/ccAuthorizationResponse/message").InnerText == "Approved")
            {
                XmlNode Text = (xmlResponse.SelectSingleNode("/forwardItResponse/ccAuthorizationResponse/transactionId"));
                lblAuthTransID.Text = Text.InnerText;
                XmlNode Text2 = (xmlResponse.SelectSingleNode("/forwardItResponse/ccAuthorizationResponse/authCode"));
                lblPreauthCode.Text = Text2.InnerText;
                //        result = "The order has been created. Assigned order number: " + xmlResponse.SelectSingleNode("//UDOARequest/Header/OrderNumber").InnerText;
                //        //result = xmlResponse.OuterXml;
            }
            else
            {
                XmlNode Text = (xmlResponse.SelectSingleNode("/forwardItResponse/ccAuthorizationResponse/Response"));
                lblCrap.Text = Text.InnerText;
                //lblCrap.Text = xmlResponse.InnerXml;
                //        result = "The order has been queued.";
            }
            //xmlResponse.Save(@"C:\Users\Aaron.Christensen.FOCUSSERVICES\Documents\datapak_responsetest.xml");
        }
        
        return result;
        //return true;
    }

    private XmlElement CreateElement(XmlDocument doc, string name, string value, string attrName, string attrValue)
    {
        XmlElement element = doc.CreateElement(name);
        if (!String.IsNullOrEmpty(value))
        {
            element.InnerText = System.Security.SecurityElement.Escape(value);
        }
        if (!String.IsNullOrEmpty(attrName))
        {
            element.SetAttribute(attrName, System.Security.SecurityElement.Escape(attrValue));
        }
        return element;
    }

    private string PostRequest(string url, string data, ref int errorNumber, ref string errorMessage)
    {
        // Create the Web Request Object 
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        request.Timeout = 60000;
        request.ContentType = "text/xml; charset=utf-8";

        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
        request.ContentLength = bytes.Length;

        Stream outputStream = request.GetRequestStream();
        outputStream.Write(bytes, 0, bytes.Length);
        outputStream.Close();

        WebResponse response = null;
        try
        {
            response = request.GetResponse();
            errorNumber = 0;
        }
        catch (System.Net.WebException e)
        {
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                errorNumber = (int)((HttpWebResponse)e.Response).StatusCode;
                errorMessage = ((HttpWebResponse)e.Response).StatusDescription;
                //get the response anyway
                response = e.Response;
            }
            else
            {
                errorNumber = 2;
                errorMessage = e.Message;
            }
        }
        catch (Exception e)
        {
            errorNumber = 1;
            errorMessage = e.Message;
        }

        if (response != null)
        {
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            return reader.ReadToEnd();
        }
        else
        {
            return "";
        }
    }

    public string DataPakOrderSubmission()  //originally was public string
    {
        int errNum = 0;
        string errDesc = "";
        string result = "";

        XmlDocument xmlOrderRequest = new XmlDocument();
        XmlDeclaration declaration = xmlOrderRequest.CreateXmlDeclaration("1.0", "UTF-8", null);
        xmlOrderRequest.AppendChild(declaration);

        XmlElement root2 = xmlOrderRequest.CreateElement("DatapakServices");
        root2.SetAttribute("method", "submit_order");

        XmlElement source = CreateElement(xmlOrderRequest, "Source", null, null, null);
        source.AppendChild(CreateElement(xmlOrderRequest, "ID", "BRAINFS", null, null));
        //source.AppendChild(CreateElement(xmlOrderRequest, "Username", "johndoe", null, null));
        //source.AppendChild(CreateElement(xmlOrderRequest, "Password", "x42342343", null, null));
        source.AppendChild(CreateElement(xmlOrderRequest, "username", "ailAPIo", null, null));
        source.AppendChild(CreateElement(xmlOrderRequest, "password", "083iwkh", null, null));
        root2.AppendChild(source);

        XmlElement order = CreateElement(xmlOrderRequest, "Order", null, null, null);
        order.SetAttribute("method", "order");
        order.AppendChild(CreateElement(xmlOrderRequest, "CompanyNumber", "204", null, null));
        order.AppendChild(CreateElement(xmlOrderRequest, "ProjectNumber", "001", null, null));
        order.AppendChild(CreateElement(xmlOrderRequest, "OrderNumber", Session["listid"].ToString(), null, null));
        order.AppendChild(CreateElement(xmlOrderRequest, "SourceCode", "121", null, null));
        
        
          if (cbDownsell2.Checked && ddlDeluxeQty.SelectedIndex == 0)
            {
                if (cbExtraDVDs.Checked)
                {
                    order.AppendChild(CreateElement(xmlOrderRequest, "TrackingCode", "225I", null, null));
                }
                else
                {
                    order.AppendChild(CreateElement(xmlOrderRequest, "TrackingCode", "225H", null, null));
                }
                
            }
            else if (cbDownsell.Checked && !cbExtraDVDs.Checked && !cbDownsell2.Checked)
            {
                order.AppendChild(CreateElement(xmlOrderRequest, "TrackingCode", "225G", null, null));
            }
        
        else
        {
            order.AppendChild(CreateElement(xmlOrderRequest, "TrackingCode", "222E", null, null));
        }
    
        //order.AppendChild(CreateElement(xmlOrderRequest, "TrackingCode", "100", null, null));
        order.AppendChild(CreateElement(xmlOrderRequest, "MediaCode", "33", null, null));
        order.AppendChild(CreateElement(xmlOrderRequest, "OrderDate", string.Format("{0:MM/dd/yyyy}", System.DateTime.Today), null, null));
        order.AppendChild(CreateElement(xmlOrderRequest, "OrderTime", date1.ToString("HH:mm"), null, null));
        order.AppendChild(CreateElement(xmlOrderRequest, "ShippingMethod", shippingmethod(), null, null));
        
        XmlElement billinginfo = CreateElement(xmlOrderRequest, "BillingInfo", null, null, null);
        billinginfo.AppendChild(CreateElement(xmlOrderRequest, "FirstName", tbFirstName.Text, null, null));
        billinginfo.AppendChild(CreateElement(xmlOrderRequest, "LastName", tbLastName.Text, null, null));
        billinginfo.AppendChild(CreateElement(xmlOrderRequest, "Address1", tbAddr.Text, null, null));
        billinginfo.AppendChild(CreateElement(xmlOrderRequest, "Address2", tbAddr2.Text, null, null));
        billinginfo.AppendChild(CreateElement(xmlOrderRequest, "City", ddlCity.SelectedItem.Text, null, null));
        billinginfo.AppendChild(CreateElement(xmlOrderRequest, "State", ddlState.SelectedItem.Text, null, null));
        billinginfo.AppendChild(CreateElement(xmlOrderRequest, "ZipCode", tbZip.Text, null, null));
        if (ddlCountry.SelectedItem.Text == "USA")
        {
            billinginfo.AppendChild(CreateElement(xmlOrderRequest, "Country", "US", null, null));
        }
        if (ddlCountry.SelectedItem.Text == "CANADA")
        {
            billinginfo.AppendChild(CreateElement(xmlOrderRequest, "Country", "CA", null, null));
        }
        billinginfo.AppendChild(CreateElement(xmlOrderRequest, "Phone", tbPhone.Text, null, null));
        billinginfo.AppendChild(CreateElement(xmlOrderRequest, "Email", tbEmail.Text, null, null));
        order.AppendChild(billinginfo);

        if (cbShipping.Checked)
        {
            XmlElement shippingInfo = CreateElement(xmlOrderRequest, "ShippingInfo", null, null, null);
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "FirstName", tbFirstName.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "LastName", tbLastName.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Address1", tbShipAddr.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Address2", tbShipaddr2.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "City", ddlShipCity.SelectedItem.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "State", ddlShipState.SelectedItem.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "ZipCode", tbShipZip.Text, null, null));
            if (ddlShipCountry.SelectedItem.Text == "USA")
            {
                shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Country", "US", null, null));
            }
            if (ddlShipCountry.SelectedItem.Text == "CANADA")
            {
                shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Country", "CA", null, null));
            }
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Phone", tbPhone.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Email", tbEmail.Text, null, null));
            order.AppendChild(shippingInfo);
        }
        else
        {
            XmlElement shippingInfo = CreateElement(xmlOrderRequest, "ShippingInfo", null, null, null);
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "FirstName", tbFirstName.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "LastName", tbLastName.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Address1", tbAddr.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Address2", tbAddr2.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "City", ddlCity.SelectedItem.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "State", ddlState.SelectedItem.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "ZipCode", tbZip.Text, null, null));
            if (ddlCountry.SelectedItem.Text == "USA")
            {
                shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Country", "US", null, null));
            }
            if (ddlCountry.SelectedItem.Text == "CANADA")
            {
                shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Country", "CA", null, null));
            }
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Phone", tbPhone.Text, null, null));
            shippingInfo.AppendChild(CreateElement(xmlOrderRequest, "Email", tbEmail.Text, null, null));
            order.AppendChild(shippingInfo);
        }


        XmlElement paymentinfo = CreateElement(xmlOrderRequest, "PaymentInfo", null, null, null);
        if (ddlPaymentType.SelectedValue == "CC")
        {
            if (ddlCardType.SelectedValue == "V")
            {
                paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "PaymentType", "VI", null, null));
            }
            if (ddlCardType.SelectedValue == "A")
            {
                paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "PaymentType", "AM", null, null));
            }
            if (ddlCardType.SelectedValue == "D")
            {
                paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "PaymentType", "DI", null, null));
            }
            if (ddlCardType.SelectedValue == "M")
            {
                paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "PaymentType", "MA", null, null));
            }
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "CardNumber", tbCCNumber.Text, null, null));
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "ExpirationMonth", tbExpDate.Text.Substring(0, 2), null, null));
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "ExpirationYear", "20" + tbExpDate.Text.Substring(2, 2), null, null));
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "CVV", tbCCV.Text, null, null));
            
        }
        else
        {
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "PaymentType", null, null, null));
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "CardNumber", null, null, null));
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "ExpirationMonth", null, null, null));
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "ExpirationYear", null, null, null));
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "CVV", null, null, null));
        }
        paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "TransactionID", lblAuthTransID.Text, null, null));                  //get from preauth()
        paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "AuthCode", lblPreauthCode.Text, null, null));                        //get from preauth()
        if (ddlPaymentType.SelectedValue == "EC")
        {
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "RoutingNumber", "", null, null));
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "AccountNumber", "", null, null));
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "CheckNumber", "", null, null));
        }
        double shippingcharge = 0.0;

        if (!cbShipping.Checked) //if shipping info is visible
        {
            if (ddlState.SelectedItem.Text == "AK" || ddlState.SelectedItem.Text == "HI" || ddlState.SelectedItem.Text == "VI" || ddlState.SelectedItem.Text == "GU" || ddlState.SelectedItem.Text == "PR" || ddlCountry.SelectedItem.Text == "CANADA")
            {
                shippingcharge += 10.0;
            }
        }
        else
        {
            if (ddlShipState.SelectedItem.Text == "AK" || ddlShipState.SelectedItem.Text == "HI" || ddlShipState.SelectedItem.Text == "VI" || ddlShipState.SelectedItem.Text == "GU" || ddlShipState.SelectedItem.Text == "PR" || ddlShipCountry.SelectedItem.Text == "CANADA")
            {
                shippingcharge += 10.0;
            }
        }        

        if (cbDownsell2.Checked && ddlDeluxeQty.SelectedIndex == 0)
        {
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "NumberOfPayments", "2", null, null));
            //paymentinfo.SetAttribute("number", "1");
            //if (cbRush.Checked)
            //{
            //    XmlElement payment = CreateElement(xmlOrderRequest, "Payment", (((DataAccess)Session["App"]).GetOrderTotal() - 15.0).ToString(), null, null);
            //    payment.SetAttribute("number", "1");
            //    paymentinfo.AppendChild(payment);
            //}
            //else
            //{
            
                XmlElement payment = CreateElement(xmlOrderRequest, "Payment", (((DataAccess)Session["App"]).GetOrderTotal() + shippingcharge).ToString(), null, null);
                payment.SetAttribute("number", "1");
                paymentinfo.AppendChild(payment);
            //}
            XmlElement payment2 = CreateElement(xmlOrderRequest, "Payment", (149.99 * ddlQty.SelectedIndex).ToString(), null, null);
            payment2.SetAttribute("number", "2");
            paymentinfo.AppendChild(payment2);
        }
        else
        {
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "NumberOfPayments", "1", null, null));
            //if (cbRush.Checked)
            //{
            //    XmlElement payment = CreateElement(xmlOrderRequest, "Payment", (((DataAccess)Session["App"]).GetOrderTotal() - 15.0).ToString(), null, null);
            //    payment.SetAttribute("number", "1");
            //    paymentinfo.AppendChild(payment);
            //}
            //else
            //{
            //    XmlElement payment = CreateElement(xmlOrderRequest, "Payment", (((DataAccess)Session["App"]).GetOrderTotal()).ToString(), null, null);
            //    payment.SetAttribute("number", "1");
            //    paymentinfo.AppendChild(payment);
            //}
            if (ddlDeluxeQty.SelectedIndex > 0)
            {
                XmlElement payment = CreateElement(xmlOrderRequest, "Payment", (((DataAccess)Session["App"]).GetOrderTotal() + shippingcharge).ToString(), null, null);
                payment.SetAttribute("number", "1");
                paymentinfo.AppendChild(payment);
            }
            else
            {
                XmlElement payment = CreateElement(xmlOrderRequest, "Payment", (((DataAccess)Session["App"]).GetOrderTotal() + shippingcharge).ToString(), null, null);
                payment.SetAttribute("number", "1");
                paymentinfo.AppendChild(payment);
            }
            
        }
        //paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "Payment", "415.27", null, null));
        //paymentinfo.SetAttribute("number", "1");
        double total = ((DataAccess)Session["App"]).GetOrderTotal();
        if (cbRush.Checked)
        {
            total -= 15.0;
        }
        if (cbDownsell2.Checked && ddlDeluxeQty.SelectedIndex == 0)
        {
            total += 149.99 * ddlQty.SelectedIndex;
        }
       
        paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "MerchandiseTotal", total.ToString(), null, null));  //should be subtotal?  main prod + upsells?

        paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "ShippingCharge", shippingcharge.ToString(), null, null));
        
        //paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "ShippingCharge", "0.00", null, null));
        if (cbRush.Checked)
        {
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "RushCharge", "15.00", null, null));
            total += 15.0;
        }
        else
        {
            paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "RushCharge", "0.00", null, null));
        }
        paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "PriorityHandling", "0.00", null, null));
        paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "SalesTax", "0.00", null, null));        //need to get from Avalara
        paymentinfo.AppendChild(CreateElement(xmlOrderRequest, "OrderTotal", (total + shippingcharge).ToString(), null, null));     //subtotal + tax + shipping
        order.AppendChild(paymentinfo);
        
                                                                                                                //repeat Item and Continuity as needed
        int itemnumber = 1;
        foreach (DataRow r in ((DataAccess)Session["App"]).GetOrder().Rows)
        {
            if (r["ProductTypeID"].ToString() == "1")
            {
                continue;
            }
            XmlElement item = CreateElement(xmlOrderRequest, "Item", null, null, null);
            item.AppendChild(CreateElement(xmlOrderRequest, "ItemCode", (((DataAccess)Session["App"]).GetProducts("ProductID", r["ProductID"].ToString())).Rows[0]["Group1"].ToString(), null, null));
            item.AppendChild(CreateElement(xmlOrderRequest, "Sequence", (((DataAccess)Session["App"]).GetProducts("ProductID", r["ProductID"].ToString())).Rows[0]["Group2"].ToString(), null, null));
            item.AppendChild(CreateElement(xmlOrderRequest, "Quantity", r["Quantity"].ToString(), null, null));
            if (r["ProductID"].ToString() == "490")
            {
                item.AppendChild(CreateElement(xmlOrderRequest, "Price", (Convert.ToDouble(r["BaseRevenue"]) + 149.99).ToString(), null, null));
            }
            else
            {
                item.AppendChild(CreateElement(xmlOrderRequest, "Price", r["BaseRevenue"].ToString(), null, null));
            }
            if (r["ProductTypeID"].ToString() == "2")
            {
                item.AppendChild(CreateElement(xmlOrderRequest, "Upsell", "Y", null, null));
            }
            else
            {
                item.AppendChild(CreateElement(xmlOrderRequest, "Upsell", "N", null, null));
            }
            item.AppendChild(CreateElement(xmlOrderRequest, "GiftWrap", "N", null, null));
            item.AppendChild(CreateElement(xmlOrderRequest, "GiftWrapCharge", "0.00", null, null));
            item.AppendChild(CreateElement(xmlOrderRequest, "GiftWrapFrom", "", null, null));
                //XmlElement continuity = CreateElement(xmlOrderRequest, "Continuity", null, null, null);
                //continuity.AppendChild(CreateElement(xmlOrderRequest, "ItemCode", (((DataAccess)Session["App"]).GetProducts("ProductID", r["ProductID"].ToString())).Rows[0]["Group1"].ToString(), null, null));
                //continuity.AppendChild(CreateElement(xmlOrderRequest, "Sequence", (((DataAccess)Session["App"]).GetProducts("ProductID", r["ProductID"].ToString())).Rows[0]["Group2"].ToString(), null, null));
                //continuity.AppendChild(CreateElement(xmlOrderRequest, "Quantity", r["Quantity"].ToString(), null, null));
                //continuity.AppendChild(CreateElement(xmlOrderRequest, "Price", r["BaseRevenue"].ToString(), null, null));
                //continuity.AppendChild(CreateElement(xmlOrderRequest, "ShippingCharge", "0.00", null, null));
                //if (r["ProductID"].ToString() == "490")
                //{
                //    continuity.AppendChild(CreateElement(xmlOrderRequest, "NumberOfPayments", "2", null, null));
                //}
                //else
                //{
                //    continuity.AppendChild(CreateElement(xmlOrderRequest, "NumberOfPayments", "1", null, null));
                //}
                //item.AppendChild(continuity);
            order.AppendChild(item);
            itemnumber++;
        }
        root2.AppendChild(order);

        xmlOrderRequest.AppendChild(root2);
        
        //xmlOrderRequest.Save(@"C:\Users\Aaron.Christensen.FOCUSSERVICES\Documents\datapak_ordersubmission_test.xml");                                                    //.............comment out for production!~!
        ((DataAccess)Session["App"]).PutCallData("xmlOrder", xmlOrderRequest.OuterXml);
        
        // Send the Request to OMX
        //string orderresponse = PostRequest("HTTPS://webservices.datapakservices.com/OrderServiceTest", xmlOrderRequest.OuterXml, ref errNum, ref errDesc);     //testing
        string orderresponse = PostRequest("HTTPS://webservices.datapakservices.com/OrderServiceV1", xmlOrderRequest.OuterXml, ref errNum, ref errDesc);     //production
        // Handle the HTTP errors
        if (errNum != 0)
        {
            if (errNum == 500)
            {
                // Handle critical OMX errors
                if (!String.IsNullOrEmpty(orderresponse))
                {
                    //string errors = "";
                    XmlDocument xmlResponse = new XmlDocument();
                    xmlResponse.LoadXml(orderresponse);
                    //foreach (XmlNode error in xmlResponse.SelectNodes("//ErrorData/Error"))
                    //    errors += error.InnerText + " - ";
                    //foreach (XmlNode error in xmlResponse.SelectNodes("//Result/Reference"))
                    //    errors += "PX error reference: " + error.InnerText + " - ";
                    //throw new Exception(errors);

                }
            }
            throw new Exception("ERROR " + errNum + ": " + errDesc);
        }

        // Handle the response content
        if (!String.IsNullOrEmpty(orderresponse))
        {
            XmlDocument xmlResponse = new XmlDocument();
            xmlResponse.LoadXml(orderresponse);

            if (xmlResponse.SelectSingleNode("/DatapakServices/Order/Result/Description").InnerText == "Order successfully submitted.")
            {
                XmlNode Text3 = (xmlResponse.SelectSingleNode("/DatapakServices/Order/Result/Code"));
                Label2.Text = Text3.InnerText;
                result = "Success";
                //        result = "The order has been created. Assigned order number: " + xmlResponse.SelectSingleNode("//UDOARequest/Header/OrderNumber").InnerText;
                //        //result = xmlResponse.OuterXml;
            }
            else
            {
                XmlNode Text3 = (xmlResponse.SelectSingleNode("/DatapakServices/Order/Result/Description"));
                Label2.Text = Text3.InnerText;
                result = Text3.InnerText;
                //lblCrap.Text = xmlResponse.InnerXml;
                //        result = "The order has been queued.";
            }

            //xmlResponse.Save(@"C:\Users\Aaron.Christensen.FOCUSSERVICES\Documents\datapak_ordersubmission_responsetest.xml");
        }
        else
            result = "Response Empty or NULL";

        return result;
        //return true;
    }

   

    //private string PostRequest(string url, string data, ref int errorNumber, ref string errorMessage)
    //{
    //    // Create the Web Request Object 
    //    WebRequest request = WebRequest.Create(url);
    //    request.Method = "POST";
    //    request.Timeout = 60000;
    //    request.ContentType = "text/xml; charset=utf-8";

    //    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
    //    request.ContentLength = bytes.Length;

    //    Stream outputStream = request.GetRequestStream();
    //    outputStream.Write(bytes, 0, bytes.Length);
    //    outputStream.Close();

    //    WebResponse response = null;
    //    try
    //    {
    //        response = request.GetResponse();
    //        errorNumber = 0;
    //    }
    //    catch (System.Net.WebException e)
    //    {
    //        if (e.Status == WebExceptionStatus.ProtocolError)
    //        {
    //            errorNumber = (int)((HttpWebResponse)e.Response).StatusCode;
    //            errorMessage = ((HttpWebResponse)e.Response).StatusDescription;
    //            //get the response anyway
    //            response = e.Response;
    //        }
    //        else
    //        {
    //            errorNumber = 2;
    //            errorMessage = e.Message;
    //        }
    //    }
    //    catch (Exception e)
    //    {
    //        errorNumber = 1;
    //        errorMessage = e.Message;
    //    }

    //    if (response != null)
    //    {
    //        Stream responseStream = response.GetResponseStream();
    //        StreamReader reader = new StreamReader(responseStream);
    //        return reader.ReadToEnd();
    //    }
    //    else
    //    {
    //        return "";
    //    }
    //}
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label3.Text = DataPakOrderSubmission();
    }
    protected void cbDownsell_CheckedChanged(object sender, EventArgs e)
    {
        pnlDownsell.Visible = !pnlDownsell.Visible;
        if (!cbDownsell.Checked)
        {
            cbDownsell2.Checked = false;
            pnlDownsell2.Visible = false;
            cbExtraDVDs.Checked = false;
            ddlDeluxeQty.SelectedIndex = 0;
        }
    }
    protected void cbDownsell2_CheckedChanged(object sender, EventArgs e)
    {
        pnlDownsell2.Visible = !pnlDownsell2.Visible;
        if (!cbDownsell2.Checked)
        {
            cbExtraDVDs.Checked = false;
            ddlDeluxeQty.SelectedIndex = 0;
        }
        //pnlTrial.Visible = !pnlTrial.Visible;
    }
    
    protected void cbMocha_CheckedChanged(object sender, EventArgs e)
    {
        lblMochaYes.Visible = true;
        lblMochaYes.Text = "Because this is an online community and a fully digital service, we will be sending you your log in information directly to your email address. Can you verify that address for me now: [capture email: REQUIRED!] Thank you, you will be receiving an email welcome letter very soon.";
        cbMocha.Checked = false;
        cbMocha.Visible = false;
        ddlMocha.SelectedIndex = 1;
        //lblMochaYes.Visible = true;
        //lblMochaYes.Text = "Because this is an online community and a fully digital service, we will be sending you your log in information directly to your email address. Can you verify that address for me now: [capture email: REQUIRED!] Thank you, you will be receiving an email welcome letter very soon.";
    }
    protected void ddlSoundHealth_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlSoundHealth.SelectedItem.Text == "No")
        {
            lblSound.Visible = true;
            lblSound.Text = "Now, <caller’s name>, have you ever had days where you just can’t concentrate? Or, maybe there’s a particular school subject <you / your child> struggles with? These are great opportunities to use Sound Health. I tell you what, normally we only sell this as a 3 CD set because it’s been proven so valuable across a wide range of mental functions. The 3 CD set is actually a bargain at $29.95. Normally, they cost $14.95 per CD, so you’re saving 33% when you buy the complete set today. But, if there’s a particular CD you were interested in, I’m happy to sell it to you at the regular price. Would you like the 3 CD set at 33% off the regular price or just 1 CD today?";
            ddlSound2.Visible = true;
            rblMusic.SelectedIndex = -1;
            ddlSound2_SelectedIndexChanged(null, null);
        }
        else
        {
            lblSound.Visible = false;
            lblSound2.Visible = false;
            ddlSound2.Visible = false;
            ddlSound2.SelectedIndex = 0;
            rblMusic.SelectedIndex = -1;
            rblMusic.Visible = false;
        }
        Page.SetFocus(ddlSoundHealth);
    }
    protected void ddlSound2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlSound2.SelectedItem.Text == "1")
        {
            lblSound2.Visible = true;
            lblSound2.Text = "Great, which CD were you most interested in: Music for Thinking, Music for Learning or Music for Concentration";
            rblMusic.Visible = true;
        }
        if (ddlSound2.SelectedItem.Text == "3" || ddlSound2.SelectedItem.Text == "Choose One")
        {
            lblSound2.Visible = false;
            rblMusic.Visible = false;
        }
        Page.SetFocus(ddlSound2);
    }
    protected void ddlPlaybookQty_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void ddlMocha_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlMocha.SelectedItem.Text == "Yes")
        {
            lblMochaYes.Visible = true;
            lblMochaYes.Text = "Because this is an online community and a fully digital service, we will be sending you your log in information directly to your email address. Can you verify that address for me now: [capture email: REQUIRED!] Thank you, you will be receiving an email welcome letter very soon.";
        }
        if (ddlMocha.SelectedItem.Text == "No")
        {
            lblMochaYes.Visible = true;
            lblMochaYes.Text = "Many colleges today require a certain level of a second language to guarantee registration. This is a tool to help your child learn a new language in the most fun and entertaining way possible. You can learn right with your child, or you can use it yourself. Think of all the possibilities for the future if you and/or your child do really understand how to speak, Spanish, French, Mandarin, or another foreign language? As all businesses go global, the need for a second and maybe a third language increases. With LiveMocha, you have an award winning program that is currently helping 12 million people learn. You are completely covered and can try this system for a full 30 days. If you are not satisfied for any reason, feel free to give customer service a call, and you will have a full refund for this offer. Because this is such a win win situation for you, let’s go ahead and get this started right now, oK?";
            cbMocha.Visible = true;
        }
        if (ddlMocha.SelectedItem.Text == "Choose One")
        {
            lblMochaYes.Visible = false;
            cbMocha.Visible = false;
            cbMocha.Checked = false;
            
        }
    }
    protected void ddlDeluxeQty_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlDeluxeQty.SelectedIndex > 0)
        {
            cbExtraDVDs.Checked = false;
            pnlDeluxe.Visible = false;
        }
        else
        {
            pnlDeluxe.Visible = true;
        }
    }

    private string shippingmethod()
    {
        string s = "";
        if (!cbShipping.Checked) //if shipping info is visible
        {
            if (cbRush.Checked)
            {
                s = "03";
            }
            else if (ddlState.SelectedItem.Text == "AK" || ddlState.SelectedItem.Text == "HI" || ddlState.SelectedItem.Text == "VI" || ddlState.SelectedItem.Text == "GU" || ddlState.SelectedItem.Text == "PR" || ddlCountry.SelectedItem.Text == "CANADA")
            {
                s = "09";
            }
            else
            {
                s = "01";
            }
        }
        else
        {
            if (cbRush.Checked)
            {
                s = "03";
            }
            else if (ddlShipState.SelectedItem.Text == "AK" || ddlShipState.SelectedItem.Text == "HI" || ddlShipState.SelectedItem.Text == "VI" || ddlShipState.SelectedItem.Text == "GU" || ddlShipState.SelectedItem.Text == "PR" || ddlShipCountry.SelectedItem.Text == "CANADA")
            {
                s = "09";
            }
            else
            {
                s = "01";
            }
        }
        return s;
    }
    
    
}